package com.codeoss.framework.workflow.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.IScriptServiceStore;
import com.codeoss.framework.workflow.context.WorkflowContext;
import com.codeoss.framework.workflow.def.LineDef;
import com.codeoss.framework.workflow.def.NodeDef;
import com.codeoss.framework.workflow.service.ILineService;
import com.codeoss.framework.workflow.service.INodeService;

@Service
public class LineService implements ILineService ,ApplicationContextAware{
    private ApplicationContext applicationContext;
    @Autowired
    private IScriptServiceStore scriptServiceStore;
	@Override
	@Transactional
	public void take(WorkflowContext workflowContext, LineDef lineDef) {
		// TODO Auto-generated method stub
		NodeDef toNodeDef=lineDef.getToNode();
		workflowContext.setNodeDef(toNodeDef);
		
		Expression takeEventExpression=lineDef.getTakeEventExpression();
		if(takeEventExpression!=null) {
			Map<String,Object> bindingMap=new HashMap<String,Object>();
			bindingMap.put("workflowContext", workflowContext);
			scriptServiceStore.getScriptService(takeEventExpression).eval(takeEventExpression.getScript(), bindingMap);	
		}
		INodeService nodeService=(INodeService)applicationContext.getBean(toNodeDef.getType()+"NodeService");
		nodeService.start(workflowContext);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		this.applicationContext=applicationContext;
	}

}
